package pl.edu.agh.pp.ldap;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Ldap {
	
	private UserDAO userDAO;
	
	public Ldap() {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        this.userDAO = (UserDAO) context.getBean("userdao");
	}
	
	public boolean createUser(User user) {
		return userDAO.create(user);
	}

	public void deleteUser(User user) {
		userDAO.delete(user);
	}
	
	public void updateUser(User user) {
		userDAO.update(user);
	}
	
	public boolean authenticate(User user) {
		return userDAO.authenticate(user);
	}
	
	public List<User> getAllUsers() {
		return userDAO.getAll();
	}
	
	public User getUserByLogin(String login) {
		return userDAO.getByLogin(login);
	}
	
	public List<String> getServersList() {
		return userDAO.getServersList();
	}

	public static void main( String[] args ) {
		Ldap ldap = new Ldap();
		
    	User user = new User();
    	user.setUsername("bubsa");
    	user.setPassword("huba");
    	user.setAddress("adr");
    	
    	ldap.createUser(user);
    	
    	if(ldap.authenticate(user)) {
    		System.out.println("YEAH");
    	}
    	/*
    	user.setAddress("localhosttest3");
    	ldap.updateUser(user);
    	
    	user.setUsername("hucpatest2");
    	ldap.createUser(user);
    	
    	ldap.deleteUser(user);
    	
    	for(User usr : ldap.getAllUsers()) System.out.println(usr.getUsername()+" "+usr.getAddress());*/ 
    }

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public List<File> getFilesList(String server) {
		List<File> filesInfo = new ArrayList<File>();
		User user = userDAO.getByAddress(server);
		if(user!=null) {
			filesInfo.addAll(user.getFilesList());
		}
		return filesInfo;
	}

	public void resetUserAddress(String username, String localServerAddress) {
		for(User user : userDAO.getAll()) {
			if(user.getAddress().trim().startsWith(localServerAddress.trim()) && !user.getUsername().trim().startsWith(username.trim())) {
				user.setAddress(" ");
				updateUser(user);
			}
		}	
	}
	
	
	
	
}
